package com.question.business.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.user.entity.UserOrg;
import com.question.business.user.mapper.UserOrgMapper;
import com.question.business.user.service.IUserOrgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 用户机构服务实现类
 *
 * @author star
 * @since 2023-09-15
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserOrgServiceImpl extends ServiceImpl<UserOrgMapper, UserOrg> implements IUserOrgService {

    /**
     * 用户机构查询
     *
     * @param userId 用户ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryOrgByUserId(String userId) {
        return baseMapper.queryOrgByUserId(userId);
    }

    /**
     * 机构用户查询
     *
     * @param orgId 机构ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryUserByOrgId(String orgId) {
        return baseMapper.queryUserByOrgId(orgId);
    }

    /**
     * 用户机构新增数据
     *
     * @param userId 用户ID
     * @param orgIds 机构ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserOrg(String userId, List<String> orgIds) {
        // 删除用户部门
        baseMapper.deleteByUserId(userId);
        handleBatchAdd(Collections.singletonList(userId), orgIds);
    }

    /**
     * 处理批量保存
     *
     * @param userIds 用户ID
     * @param orgIds  机构ID
     */
    private void handleBatchAdd(List<String> userIds, List<String> orgIds) {
        if (CollectionUtils.isNotEmpty(userIds) && CollectionUtils.isNotEmpty(orgIds)) {
            List<UserOrg> data = new ArrayList<>();
            for (String userId : userIds) {
                for (String orgId : orgIds) {
                    UserOrg entity = new UserOrg();
                    entity.setUserId(userId);
                    entity.setOrgId(orgId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 机构用户新增数据
     *
     * @param orgId   机构ID
     * @param userIds 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrgUser(String orgId, List<String> userIds) {
        // 删除部门用户
        baseMapper.deleteByOrgId(orgId);
        handleBatchAdd(userIds, Collections.singletonList(orgId));
    }
}